<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BScreenAddServiceApp
 *
 * @author jianfeng
 */
class BScreenAddServiceApp extends BUIScreen {

    //put your code here

    public function render($data = null) {
        if (!is_array($data)) {
            $data = array();
        }

        $isRenderInitialView = true;

        $model = new CreateServiceFormModel();

        if ($this->isLinkClicked('addServiceBtn')) {

            if (isset($_POST['CreateServiceFormModel'])) {
                $model->attributes = $_POST['CreateServiceFormModel'];
            }

            $result = $this->addServiceApps($model->serviceApps);
            $this->gotoUINode(Blyn::app()->getActiveService()->getId());
            yii::app()->end();
        }

        if ($isRenderInitialView) {
            $this->addRenderView('addServiceAppView', 'addServiceApp', array('model' => $model, 'screen' => $this));
            //$this->startRender();
        }
    }

    public function getServiceAppsData() {

        //$service = $this->getUINode()->getTransitVariable(BScreenCreateServiceMeta::TRANSIT_VARIABLE_NEWSERVICE);
        //$db = $service->getServiceEngine()->getDbAdapter();
        //$apps = $db->getServiceApps($service->getId());



        $service = Blyn::app()->getActiveService();

        $db = Blyn::app()->getAppDb();

        $apps = $db->getVisibleServiceApps($service);

        $myApps = Blyn::app()->getActiveService()->getServiceApps();

        $ids = array();

        foreach ($apps as $app) {
            array_push($ids, $app->getId());
        }

        foreach ($myApps as $app) {
            $appId = $app->getId();
            if (in_array($appId, $ids)) {
                unset($apps[$appId]);
            }
        }

        $data = array();

        foreach ($apps as $app) {
            if ($app->isVisible($service)) {
                $data[$app->getId()] = $app->getName();
            }
        }
        return $data;
    }

    public function addServiceApps($sApps) {
        $serviceId = Blyn::app()->getActiveService()->getId();

        foreach ($sApps as $appId) {
            $result = Blyn::app()->getActiveServiceApp()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $serviceId, 'App' => $appId));
        }      
    }

}

?>
